﻿using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web.Mvc;
using Beeldbankmvc.Code;
using Beeldbankmvc.Models;
using Beeldbankmvc.ViewModels;
using System.IO;

namespace Beeldbankmvc.Controllers
{
    [HandleErrorWithELMAH]
    public class CollectionController : Controller
    {
        //
        // GET: /Collection/
        [Authorize(Roles="Administrator")]
        public ActionResult Index()
        {
            CollectionRepository collRepository = new CollectionRepository();
            CollectionViewModel collVM = new CollectionViewModel();

            collVM.collectionObjects = collRepository.FindAllSortedByName().ToList();

            return View(collVM);
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Create()
        {
            return View();
        }
        
        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Create(CollectionModel model)
        {
            try
            {
                CollectionRepository collRepository = new CollectionRepository();
                if (Request.Form["AppApproved"] != null && Request.Form["AppApproved"].Equals("true"))
                    model.AppApproved = true;
                else
                    model.AppApproved = false;
                collRepository.Add(model);
                collRepository.Save();

                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id)
        {
            CollectionRepository collRepository = new CollectionRepository();
            CollectionModel coll = collRepository.FindOne(id);

            return View(coll);
        }

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(CollectionModel model)
        {
            if (ModelState.IsValid)
            {
                CollectionRepository collRepository = new CollectionRepository();
                collRepository.SaveThumbnail(Request, model);
                if (Request.Form["AppApproved"] != null && Request.Form["AppApproved"].Equals("true"))
                    model.AppApproved = true;
                else
                    model.AppApproved = false;
                collRepository.Update(model);
                collRepository.Save();
            }

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id)
        {
            try
            {
                CollectionRepository collRepository = new CollectionRepository();
                CollectionModel model = collRepository.FindOne(id);

                collRepository.Delete(model);                
                collRepository.Save();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult DisplayTheme(int id)
        {
            try
            {
                CollectionRepository collRepository = new CollectionRepository();
                CollectionModel model = collRepository.FindOne(id);

                // Prevent errors when specifying the wrong id for viewing
                if (model == null)
                    return null;

                // Check if a preview file exists, then return this image
                // Use cached image when present
                if (Beeldbankmvc.Helpers.Tools.getThemeImage(model) != "")
                    return new ImageResult { Image = CreateNonIndexedImage(model), ImageFormat = ImageFormat.Jpeg, cacheHeaderToNull = false };
                else
                {
                    Image noImage = Image.FromFile(Server.MapPath("/Content/Images/") + "noimage.jpg");
                    return new ImageResult { Image = noImage, ImageFormat = ImageFormat.Jpeg };
                }
            }
            catch
            {
                return null;
            }
        }

        private static Image CreateNonIndexedImage(CollectionModel model)
        {
            // based upon http://support.microsoft.com/?id=814675
            // and clarified in code in http://stackoverflow.com/questions/3661799/file-delete-failing-when-image-fromfile-was-called-prior-it-despite-making-copy
            using (var sourceImage = Image.FromFile(Beeldbankmvc.Helpers.Tools.getThemeImage(model)))
            {
                var targetImage = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb);
                using (var canvas = Graphics.FromImage(targetImage))
                {
                    canvas.DrawImageUnscaled(sourceImage, 0, 0);
                }
                return targetImage;
            }
        }
    }
}
